package com.ehouse;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.ehouse.connection.ConnectionService;
import com.ehouse.connection.ConnectionService.IConnectionResponseListener;
import com.ehouse.database.IrrigationScheduleTable;
import com.ehouse.database.LightScheduleTable;
import com.ehouse.database.TemperatureScheduleTable;
import com.ehouse.models.Settings;

public class ScheduleDetailActivity extends FragmentActivity {
	public static final String LOG_TAG = "SCHEDULE_DETAIL";
	public static final boolean DEBUG = MainActivity.DEBUG;
	int type;
	String objectId;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle(R.string.name_schedules);
		setContentView(R.layout.schedule_detail);
		String time = getIntent().getStringExtra("time");
    	String detail = getIntent().getStringExtra("detail");
    	type =getIntent().getIntExtra("type", 0);
    	objectId = getIntent().getStringExtra("objId");
    	
    	
    	TextView scheduleLabel = (TextView)findViewById(R.id.scheduleLabel);
    	TextView detailLabel = (TextView)findViewById(R.id.detailLabel);
    	scheduleLabel.setText(time);
    	detailLabel.setText(detail);
    }
	
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_schedule_detail, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_schedule_delete:
			
			switch(type){
			case 2:{
				//Send to server
				if(!DEBUG)
				serviceRef.removeRule("Irrigation", objectId, new IConnectionResponseListener() {
					
					public void responseReceived(Object data, boolean success) {
						if(success){

							IrrigationScheduleTable.delete(getContentResolver(), objectId);
							serviceRef.loadRules("Irrigation", new IConnectionResponseListener() {
								
								public void responseReceived(Object data, boolean success) {
									if(success){
										setResult(type);
										finish();
										}
								}
							});
						}
					}
				});
				break;
			}
			case 1:{
				//Send to server
				if(!DEBUG)
				serviceRef.removeRule("Temperature", objectId, new IConnectionResponseListener() {
					
					public void responseReceived(Object data, boolean success) {
						if(success){

							TemperatureScheduleTable.delete(getContentResolver());
							
							serviceRef.loadRules("Temperature", new IConnectionResponseListener() {
										
										public void responseReceived(Object data, boolean success) {
											if(success){
												setResult(type);
												finish();
											}
											}
									});
						}
					}
				});
				
				break;
			}
			case 0:{
				
				//Send to server
				if(!DEBUG)
				serviceRef.removeRule("Lights", objectId, new IConnectionResponseListener() {
					
					public void responseReceived(Object data, boolean success) {
						if(success){

							LightScheduleTable.delete(getContentResolver(), objectId);
							serviceRef.loadRules("Lights", new IConnectionResponseListener() {
								
								public void responseReceived(Object data, boolean success) {
									if(success){
										setResult(type);
										finish();
										}
								}
							});
							
						}
					}
				});
				break;
			}
			default:
				setResult(type);
				finish();
				break;
			}
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	 //Service connection
    public static ConnectionService serviceRef;
    
    
    private ServiceConnection mConnection = new ServiceConnection() {
     public void onServiceConnected(ComponentName className, 
                                    IBinder service) {
       // Called when the connection is made.
       serviceRef = ((ConnectionService.ConnectionBinder)service).getService();
       onBinding();
     }
     
     public void onServiceDisconnected(ComponentName className) {

       // Received when the service unexpectedly disconnects.
       serviceRef = null;
     }
    };
	
	public void onBinding() {
		final SharedPreferences sharedPrefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		String ip = sharedPrefs.getString(Settings.IP, "");

		if (ip.length() > 0) {
			serviceRef.openConnection(ip, new IConnectionResponseListener() {

				public void responseReceived(Object data, boolean success) {
					if (!success){
						ScheduleDetailActivity.this.runOnUiThread(new Runnable() {
						    public void run() {
						    	if(!DEBUG)
						    		startActivity(new Intent(ScheduleDetailActivity.this, PreferencesActivity.class));
								Toast.makeText(ScheduleDetailActivity.this,
								R.string.connection_error, Toast.LENGTH_LONG)
								.show();
						    }
						});

					}
				}
			});
		} else {
			startActivity(new Intent(this,
					PreferencesActivity.class));
		}
	}
	
	@Override
    public void onPause(){
    	super.onPause();
    	if(serviceRef != null){
    		serviceRef.closeConnection();
    		unbindService(mConnection);
    	}
    	serviceRef = null;
    }
	
	 @Override
	    public void onResume(){
	    	super.onResume();
	 
	        Intent bindIntent = new Intent(this, ConnectionService.class);
	        bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
	    }
	    
}
